import Axios from 'axios'
import { message } from 'antd'
import {store}  from '../store'
import { HashRouter } from 'react-router-dom'



import "./mock"

const config: any = {
    baseURL: '',
    timeout: 600000,
    headers: {
        'Content-Type': 'application/json'
    },
    // 允许跨域携带cookie
    withCredentials: true
}

const axios: any = Axios.create(config);

const router: any = new HashRouter({})

// token失效，清除用户信息并返回登录界面
const clearAll = () => {
    store.dispatch({
        type: 'SET_USER_INFO',
        payload: {userInfo: null}
    })
    router.history.replace({ pathname: '/index/home' })
}

// 请求前拦截
axios.interceptors.request.use(
    (req: any) => {
        const { token = '' } = store.getState().storeData.userInfo || {};
        req.headers.token = token
        return req
    },
    (err: any) => {
        return Promise.reject(err)
    }
)

// 返回后拦截
axios.interceptors.response.use(
    ({ data }: any): Promise<any> => {
        if(data.code && data.code === 101) {
            clearAll()
        }
        return data
    },
    (err: any) => {
        if (JSON.stringify(err).includes('401')) {
            clearAll()
        }
        message.destroy()
        return {
            code: 9999,
            msg: "网络错误"
        }
    }
)

// post请求
axios.post = (url: string, params?: any): Promise<any> =>
    axios({
        method: 'post',
        url,
        data: params
    })

// get请求
axios.get = (url: string, params?: any): Promise<any> =>
    axios({
        method: 'get',
        url,
        params
    })

// 文件流
axios.file = (method: string, url: string, params?: any): Promise<any> =>
    axios({
        method,
        url,
        params,
        responseType: 'blob'
    })

export default axios
